package me.shurufa.fragments;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import me.shurufa.R;
import me.shurufa.activities.NewDigestBookSearchActivity;
import me.shurufa.activities.NewMainActivity;
import me.shurufa.adapter.NewSearchAdapter;
import me.shurufa.event.EventObject;
import me.shurufa.model.SearchBook;
import me.shurufa.model.SearchBookListNewResponse;
import me.shurufa.model.SearchBookListResponse;
import me.shurufa.model.SearchBookNewResponse;
import me.shurufa.net.API;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.NetworkUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.pulltorefresh.SrfPtrFrameLayout;
import me.shurufa.widget.recyclerview.EndlessRecyclerOnScrollListener;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;
import me.shurufa.widget.simpledialog.SimpleDialog;

/**
 * 新建界面搜索结果列表Fragment
 *
 * @FileName: me.shurufa.fragments.SearchFragment.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-28 11:15
 */
public class NewSearchFragment extends BaseListFragment {

    @Bind(R.id.find_book_number)
    TextView findBookNumber;

    @Bind(R.id.ll_title)
    LinearLayout ll_title;

    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;

    @Bind(R.id.ptr_refresh)
    SrfPtrFrameLayout ptrRefresh;

    public String searchKey;
    private int mSearchType = -1;

    private Context mContext;
    private NewSearchAdapter searchAdapter;
    private HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter = null;
    private String pageFrom;
    private int mFromWhere;

    public static NewSearchFragment newInstance(int searchType, String isbn, int fromWhere) {
        NewSearchFragment fragment = new NewSearchFragment();
        Bundle args = new Bundle();
        args.putInt(Constants.EXTRA_SEARCH_TYPE, searchType);
        args.putString(Constants.EXTRA_SEARCH_ISBN, isbn);
        args.putInt(Constants.ARG_FROM_WHERE, fromWhere);
        fragment.setArguments(args);
        return fragment;
    }

    public String getSearchUrl() {
        String url = null;
        switch (mSearchType) {
            case Constants.SEARCH_BY_ISBN:
                url = API.SEARCH_BOOK_BY_ISBN;
                break;
            case Constants.SEARCH_BY_KEYWORD:
                url = API.SEARCH_BOOK_BY_KEYWORD;
                break;
        }
        return url;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        if (getArguments() != null) {
            mSearchType = getArguments().getInt(Constants.EXTRA_SEARCH_TYPE);
            searchKey = getArguments().getString(Constants.EXTRA_SEARCH_ISBN);
            mFromWhere = getArguments().getInt(Constants.ARG_FROM_WHERE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_new_search_list, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        //        初始化刷新
        setRefresh();

        dataList = new ArrayList();
        searchAdapter = new NewSearchAdapter(this, dataList);
        mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(searchAdapter);
        recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addOnScrollListener(mOnScrollListener);
    }

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);

            try {
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView);
                if (state == LoadingFooter.State.Loading) {
                    LogUtils.kLog().e("the state is Loading, just wait..");
                    return;
                }

                if (hasMore) {
                    // loading more
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                    loadData(pageFrom);
                } else {
                    //the end
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private void setRefresh() {
        ptrRefresh.setResistance(2.0F);
        ptrRefresh.setRatioOfHeaderHeightToRefresh(1.0F);
        ptrRefresh.setDurationToClose(300);
        ptrRefresh.setDurationToCloseHeader(1000);
        ptrRefresh.setLoadingMinTime(500);
        ptrRefresh.setPullToRefresh(false);
        ptrRefresh.setKeepHeaderWhenRefresh(true);
        ptrRefresh.disableWhenHorizontalMove(true);
        ptrRefresh.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
                boolean canbePullDown = PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, view, view1);
                return canbePullDown;
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                refresh();
            }
        });
    }

    @Override
    protected void addDataToList(BaseResponse response, boolean isNew) {
        if (mSearchType == Constants.SEARCH_BY_KEYWORD) {
            SearchBookListNewResponse resp = (SearchBookListNewResponse) response;
            if (isNew) {
                searchAdapter.clear();
            }
            searchAdapter.append(resp.data);
        } else if (mSearchType == Constants.SEARCH_BY_ISBN) {
            SearchBookNewResponse resp = (SearchBookNewResponse) response;
            if (isNew) {
                searchAdapter.clear();
            }
            searchAdapter.append(resp.data);
        }
        searchAdapter.notifyDataSetChanged();

    }

    @Override
    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, SearchBookListResponse.class);
    }

    @Override
    protected void showEmptyView() {

    }

    @Override
    protected void hideEmptyView() {

    }

    @Override
    protected void setHasMore(boolean hasMore) {

    }

    @Override
    public void refresh() {
        super.refresh();
        findBookNumber.setVisibility(View.GONE);
        ll_title.setVisibility(View.GONE);
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ptrRefresh != null && ptrRefresh.isRefreshing()) {
                    ptrRefresh.refreshComplete();
                }
            }
        }, 2000);
        onRefresh();
    }

    public void refreshShowPtr() {
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrRefresh.autoRefresh(true);
            }
        }, 400);
    }

    public void onRefresh() {
        mPage = 1;
        pageFrom = "";
        loadData(pageFrom);
    }

    private int mPage;
    private boolean hasMore = true;
    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
            loadData(pageFrom);
        }
    };

    private void loadData(final String page) {
        if (!NetworkUtils.isNetAvailable(getActivity())) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView, Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
        } else {
            RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Loading);
            if (mSearchType == Constants.SEARCH_BY_KEYWORD) {
                new RequestServerTask<SearchBookListNewResponse>(SearchBookListNewResponse.class) {
                    @Override
                    protected String requestServer() {
                        Map<String, Object> params = new HashMap<String, Object>();
                        params.put("keyword", searchKey);
                        params.put("pageFrom", page == null ? "" : page);
                        params.put("pageSize", Constants.PAGE_REQUEST_COUNT);
                        params.put("debug", "1");
                        LogUtils.kLog().e("" + page);
                        return HttpUtil.post(getSearchUrl(), params);
                    }

                    @Override
                    protected void onPostExecute(String s) {
                        super.onPostExecute(s);
                        endRefreshing();
                    }

                    @Override
                    protected void onSuccess(SearchBookListNewResponse result) {
                        try {
                            pageFrom = result.page;
                            if (result.data == null || result.data.length == 0) { // || result.data.books == null || result.data.books.length == 0) {
                                Utils.showToast(getString(R.string.not_found_book));
                                hasMore = false;
                                RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.TheEnd);
                            } else {
                                RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.Normal);
                                hasMore = true;
                                if (mPage == 1) {
                                    ll_title.setVisibility(View.VISIBLE);
                                    findBookNumber.setVisibility(View.VISIBLE);
                                    findBookNumber.setText(String.format(getString(R.string.found_book), result.total));
                                }
                                mPage++;
                                bindData(result, TextUtils.isEmpty(pageFrom));
                            }
                        } catch (Exception e) {
                        }
                    }
                }.start();
            } else if (mSearchType == Constants.SEARCH_BY_ISBN) {
                findBookNumber.setVisibility(View.GONE);
                ll_title.setVisibility(View.GONE);
                new RequestServerTask<SearchBookNewResponse>(SearchBookNewResponse.class) {
                    @Override
                    protected String requestServer() {
                        Map<String, Object> params = new HashMap<String, Object>();
                        params.put("isbn", searchKey);
                        return HttpUtil.post(getSearchUrl(), params);
                    }

                    @Override
                    protected void onPostExecute(String s) {
                        super.onPostExecute(s);
                        endRefreshing();
                    }

                    @Override
                    protected void onSuccess(SearchBookNewResponse result) {
                        if (result.data.id == 0L) {
                            searchAdapter.clear();
                            Toast.makeText(getActivity(), "未找到相关书籍", Toast.LENGTH_SHORT).show();
                        } else {
                            hasMore = false;
                            RecyclerViewStateUtils.setFooterViewState(recyclerView, LoadingFooter.State.TheEnd);
                            bindData(result, true);
                        }
                    }
                }.start();

            }
        }
    }

    public void enableRefresh(boolean value) {
        ptrRefresh.setEnabled(value);
    }

    public void endRefreshing() {
        if (ptrRefresh != null) {
            ptrRefresh.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (ptrRefresh != null) {
                        ptrRefresh.refreshComplete();
                        if (searchAdapter.getItemCount() == 0) {
                            showEmptyView();
                        }
                    }
                }
            }, 500);
        }
    }

    public void onEventMainThread(EventObject object) {
        if (object.getEventAction().equals(Constants.EVENT_STAR_BOOK)) {
            final SearchBook searchBook = object.getSearchBook();
            if (Global.DEBUG)
                Utils.showToast("bookId:" + searchBook.id);


            SimpleDialog dialog = new SimpleDialog(getActivity());
            dialog.setContentText(getString(R.string.positive_to_add));
            dialog.setAnimationEnable(true);
            dialog.setOnPositiveListener("确定", new SimpleDialog.OnPositiveListener() {
                @Override
                public void onClick(SimpleDialog dialog) {
                    dialog.dismiss();

                    new RequestServerTask<BaseResponse>(BaseResponse.class, mContext, getString(R.string.commit_pls_wait)) {
                        @Override
                        protected String requestServer() {
                            Map<String, Object> params = new HashMap<String, Object>();
                            params.put("bookId", searchBook.id);
                            return HttpUtil.post(API.ADD_BOOK_TO_SHELVES, params);
                        }

                        @Override
                        protected void onSuccess(BaseResponse result) {
                            if (result.success) {

                                if (mFromWhere == 0) {
                                    EventBus.getDefault().post(Constants.EVENT_SWITCH_MY_SHELF);
                                    ((NewDigestBookSearchActivity) mContext).finish();

                                    Intent in = new Intent(mContext, NewMainActivity.class);
                                    in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    mContext.startActivity(in);
                                } else if (Constants.TYPE_FROM_ADD_DIGEST_ADD_NOTEBOOK == mFromWhere) {
                                    Intent in = new Intent(Constants.EVENT_ADD_NOTEBOOK_FROM_ADD_DIGEST);
                                    EventBus.getDefault().post(in);
                                    ((NewDigestBookSearchActivity) mContext).finish();
                                }
                            }
                        }
                    }.start();
                }
            });

            dialog.setOnNegativeListener("取消", new SimpleDialog.OnNegativeListener() {
                @Override
                public void onClick(SimpleDialog dialog) {
                    dialog.dismiss();
                }
            });
            dialog.show();









            /* ColorDialog dialog = new ColorDialog(getActivity());
            dialog.setAnimationEnable(true);
            dialog.setTitle(getString(R.string.add_to_shelves));
            dialog.setContentText(getString(R.string.positive_to_add));
            dialog.setPositiveListener(getString(R.string.ok), new ColorDialog.OnPositiveListener() {
                @Override
                public void onClick(ColorDialog dialog) {
                    dialog.dismiss();
                    new RequestServerTask<BaseResponse>(BaseResponse.class, mContext, getString(R.string.commit_pls_wait)) {
                        @Override
                        protected String requestServer() {
                            Map<String, Object> params = new HashMap<String, Object>();
                            params.put("bookId", searchBook.id);
                            return HttpUtil.post(API.ADD_BOOK_TO_SHELVES, params);
                        }

                        @Override
                        protected void onSuccess(BaseResponse result) {
                            if (result.success) {
                                EventBus.getDefault().post(new Intent(Constants.ACTION_BOOKSHELVES_REFRESH));
                                ((NewDigestBookSearchActivity) mContext).finish();
                            }
                        }
                    }.start();
                }
            })
                    .setNegativeListener(getString(R.string.cancel), new ColorDialog.OnNegativeListener() {
                        @Override
                        public void onClick(ColorDialog dialog) {
                            dialog.dismiss();
                        }
                    }).show();*/
        }
    }
}
